#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "dlist.h"


//static pthread_rwlock_t l_lock;


int List_head_init(struct list_head * name)
{
	pthread_rwlock_init(&name->rwlock,NULL);
	name->prev=name;
	name->next=name;
	printf("List_head_init return 0\n");
	return 0;
}

static int List_add(struct list_head *new,struct list_head *prev,struct list_head *next)
{
	if(new==NULL||prev==NULL||next==NULL)
	{
		return -1;
	}
	List_head_init(new);
	int errno=0;
	if((errno=pthread_rwlock_wrlock(&new->rwlock))!=0)
	{
		return errno;
	}
	if((errno=pthread_rwlock_wrlock(&prev->rwlock))!=0)
	{
		pthread_rwlock_unlock(&new->rwlock);
		return errno;
	}
	if(prev!=next)
	{
		if((errno=pthread_rwlock_wrlock(&next->rwlock))!=0)	
		{
			pthread_rwlock_unlock(&new->rwlock);
			pthread_rwlock_unlock(&prev->rwlock);
			return errno;
		}
	}
	next->prev=new;
	new->next=next;
	new->prev=prev;
	prev->next=new;
	pthread_rwlock_unlock(&new->rwlock);
	pthread_rwlock_unlock(&prev->rwlock);
	if(prev!=next)
	{
		pthread_rwlock_unlock(&next->rwlock);
	}
	printf("List_add return 0\n");
	return 0;
}

/*
 *销毁节点
 *return:
 	sucess	0 
	fail	errno
			-1	NULL
 */
static int List_destroy_node(struct list_head *node)
{
	if(node==NULL)	
		return -1;
	pthread_rwlock_wrlock(&node->next->rwlock);
	pthread_rwlock_wrlock(&node->rwlock);
	if(node->next!=node->prev)
	{
		pthread_rwlock_wrlock(&node->prev->rwlock);
	}
	node->prev->next=node->next;
	node->next->prev=node->prev;

	pthread_rwlock_unlock(&node->rwlock);
	pthread_rwlock_unlock(&node->next->rwlock);
	if(node->next!=node->prev)
	{
		pthread_rwlock_unlock(&node->prev->rwlock);
	}
	pthread_rwlock_destroy(&node->rwlock);
	free(node);
	return 0;
}


/*
 *des:	头插
 *return:
 	sucess	0 
	fail	errno
 */
int List_add_prev(struct list_head *new,struct list_head *head)
{
	return List_add(new,head->prev,head);
}

/*
 *des:	尾插
 *return:
 	sucess	0 
	fail	errno
 */
int List_add_tail(struct list_head *new,struct list_head *head)
{
	return List_add(new,head,head->next);
}


/*
 *des:	删除节点
 *return:
 	sucess	0 
	fail	errno
			-1	NULL
 */
int List_delete_node(struct list_head *node)
{
	if(node==NULL||node->next==NULL||node->prev==NULL)	
		return -1;
	if(node==node->next&&node==node->prev)
	{
		List_destroy(node);
	}
	return List_destroy_node(node);
}

/*
 *des:	销毁
 *return:
 	sucess	0 
	fail	errno
			-1	NULL
 */
int List_destroy(struct list_head *head)
{
	if(head==NULL||head->next==NULL||head->prev==NULL)
		return -1;
	while(head)
	{
		List_destroy_node(head->next);
		if(head->next==head)
			head=NULL;
	}
	return 0;
}
